<template>
  <div class="relative text-[0.8rem]">
    <!-- 权限管理 -->
    <el-tabs v-model="tab_value" stretch @tab-change="tab_change">
      <el-tab-pane label="菜单" name="menu"></el-tab-pane>
      <el-tab-pane label="功能" name="api"></el-tab-pane>
    </el-tabs>

    <el-scrollbar
      style="height: calc(100vh - 10rem)"
      v-if="tab_value == 'menu'"
    >
      <div>
        <el-tree
          class="w-full"
          :data="menuList"
          :props="{
            label: 'title',
            children: 'children',
          }"
          :default-checked-keys="filteredKeys"
          node-key="id"
          show-checkbox
          highlight-current
          @check="handleCheckChange"
        />
      </div>
    </el-scrollbar>
    <div v-else class="w-full flex justify-between">
      <el-scrollbar class="set_height w-[30%]">
        <el-menu
          :default-active="active"
          class="w-[100%]"
          active-text-color="white"
          background-color="#F1F0F0"
          @select="handleSelect"
        >
          <el-menu-item
            v-for="(item, index) in apiList"
            :key="index"
            :index="item.apiGroup"
          >
            <span>{{ item.apiGroupName }}</span>
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
      <el-scrollbar class="w-[68%] set_height">
        <el-card v-for="(item, index) in titleList" :key="index" class="mb-1">
          <div class="w-full h-[2.5rem] flex justify-between items-center px-1">
            <el-text truncated class="w-[65%]">{{ item.description }}</el-text>
            <el-switch
              v-model="item.isDistribution"
              class="ml-2"
              style="--el-switch-on-color: #13ce66"
              @change="handleChangeStatus(item)"
            />
          </div>
        </el-card>
      </el-scrollbar>
    </div>

    <div class="absolute bottom-0 right-0" v-if="tab_value == 'menu'">
      <el-button type="primary" @click="handleSubmit">
        <el-icon><Position /></el-icon>提交权限
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetOrganMenuDistributionListReq,
  CreateOrganMenuReq,
  GetOrganApiDistributionListReq,
  CreateOrganApiReq,
} from "../../../../../../wailsjs/go/api/DeptApi";
onMounted(() => {});

const tab_value = ref("menu");

const tab_change = () => {
  if (tab_value.value == "menu") {
    getMenuList();
    titleList.value = [];
    active.value = "";
  }
  if (tab_value.value == "api") getApiList();
};

const form = ref({
  departmentId: null,
  positionId: null,
});

// 1. 菜单
const menuList = ref([]); // 菜单列表
async function getMenuList(departmentId, positionId) {
  if (departmentId) form.value.departmentId = departmentId;
  if (positionId) form.value.positionId = positionId;

  if (departmentId && positionId) {
    tab_value.value = "menu";
  }

  handleApiResponse(() =>
    GetOrganMenuDistributionListReq({
      departmentId: form.value.departmentId,
      positionId: form.value.positionId,
    })
  ).then((res) => {
    menuList.value = res.data.list || [];
  });
}

// 更改节点 isDistribution 的值
const handleCheckChange = (checkedNode, { checkedKeys }) => {
  const updateDistributionStatus = (nodes) => {
    nodes.forEach((node) => {
      node.isDistribution = checkedKeys.includes(node.id);
      if (node.children) {
        updateDistributionStatus(node.children);
      }
    });
  };
  updateDistributionStatus(menuList.value);
};

// 默认勾选 isDistribution = true 的节点
const filteredKeys = computed(() => {
  const collectIds = (nodes) => {
    return nodes.reduce((acc, node) => {
      if (node.isDistribution) {
        acc.push(node.id);
      }
      if (node.children && node.children.length) {
        acc = acc.concat(collectIds(node.children));
      }
      return acc;
    }, []);
  };
  return collectIds(menuList.value);
});

// 获取所有被勾选的节点id
const getDistributionIds = () => {
  const collectIds = (nodes) => {
    return nodes.reduce((acc, node) => {
      if (node.isDistribution) acc.push(node.id);
      if (node.children) acc.push(...collectIds(node.children));
      return acc;
    }, []);
  };
  return collectIds(menuList.value);
};

// 提交权限
const handleSubmit = () => {
  handleApiResponse(() =>
    CreateOrganMenuReq({
      ...form.value,
      sourceIds: getDistributionIds(),
    })
  ).then((res) => {
    if (res.code == 0) {
      ElMessage.success("操作成功");
    }
  });
};

// 2.功能
const apiList = ref([]);
async function getApiList() {
  handleApiResponse(() =>
    GetOrganApiDistributionListReq({
      departmentId: form.value.departmentId,
      positionId: form.value.positionId,
    })
  ).then((res) => {
    if (res.code == 0) {
      apiList.value = res.data.list || [];
      titleList.value = [];
      if (apiList.value?.length > 0) {
        handleSelect(apiList.value[0].apiGroup);
      }
    }
  });
}

const titleList = ref([]); // 右侧权限列表

const active = ref("");
const handleSelect = (key) => {
  active.value = key;
  titleList.value = apiList.value.find(
    (item) => item.apiGroup == active.value
  ).apiList;
};

const handleChangeStatus = (row) => {
  ElMessageBox.confirm("是否确认修改状态", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      CreateOrganApiReq({
        departmentId: form.value.departmentId,
        positionId: form.value.positionId,
        isDistribution: row.isDistribution,
        sourceId: row.id,
      })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
      }
    });
  });
};

const handleRemove = () => {
  menuList.value = [];
  apiList.value = [];
  titleList.value = [];
  active.value = "";
  form.value = {
    departmentId: null,
    positionId: null,
  };
};

defineExpose({
  getMenuList,
  handleRemove,
});
</script>

<style scoped lang="scss">
.el-menu-item.is-active {
  background-color: var(--theme-color) !important;
  /* 如果需要渐变背景 */
  // background: linear-gradient(
  //   var(--theme-color) 0%,
  //   #ffffff 100%
  // ) !important;
}

.set_height {
  height: calc(100vh - 10.5rem);
}
</style>